﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

namespace ApiPlugin
{
    public static class CustomExceptionMiddleware
    {
        /// <summary>
        /// 全局异常捕获
        /// </summary>
        public static IApplicationBuilder UseCustomExceptionHandler(this IApplicationBuilder app)
        {
            return app.UseExceptionHandler(ap =>
            {
                ap.Use(ExceptionHandler);
            });
        }

        private static async Task ExceptionHandler(HttpContext httpContext, Func<Task> next)
        {
            var exceptionDetails = httpContext.Features.Get<IExceptionHandlerFeature>();
            var ex = exceptionDetails?.Error;

            if (ex != null)
            {
                httpContext.Response.ContentType = "application/json";
                var stream = httpContext.Response.Body;
                await JsonSerializer.SerializeAsync(stream, new { Code = 500, Msg = $"error:{ex.ToString()};StackTrace:{ex.StackTrace}" });
            }
        }
    }
}
